﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System;
using System.IO;

namespace Hont.HyperWigglePackage.Editor
{
    public class Echo : BaseWigglePlugins
    {
        UnityEngine.Object mTemplate;
        int mNumber;
        float mMulNumber;
        Camera mCamera;

        Vector3 mCameraCachePosition;
        Quaternion mCameraCacheRotation;



        public override void Execute(HyperWiggleEditorCore core)
        {
            base.Execute(core);

            mCamera = mCore.View.PreviewRenderUtility.camera;

            mCameraCachePosition = mCamera.transform.position;
            mCameraCacheRotation = mCamera.transform.rotation;
        }

        protected override void OnExit()
        {
        }

        protected override void OnGUI()
        {
            mTemplate = EditorGUILayout.ObjectField("Template: ", mTemplate, typeof(UnityEngine.Object), true);
            mNumber = EditorGUILayout.IntSlider("Number: ", mNumber, 0, 10);
            mMulNumber = EditorGUILayout.Slider("Mul Number: ", mMulNumber, -10f, 10f);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Cancel"))
            {
                mCamera.transform.position = mCameraCachePosition;
                mCamera.transform.rotation = mCameraCacheRotation;

                mCore.UpdatePreview();
                mCore.UpdateTimeline();
            }

            if (GUILayout.Button("Apply"))
            {
                var path = AssetDatabase.GetAssetPath(mTemplate);
                var xml = File.ReadAllText(path);
                var po = HyperWiggleUtil.XmlDeserialize<HyperWigglePO>(xml);
                var prPairArray = po.Data;

                var max = prPairArray.Length * mNumber;
                for (int i = 0; i < max && i < mCore.FrameData.Length; i++)
                {
                    var j = i % prPairArray.Length;
                    var round = 1 + i / prPairArray.Length;
                    var enhance = Mathf.Pow(mMulNumber, round);

                    var prPair = prPairArray[j];
                    prPair.RelativePosition *= enhance;
                    prPair.RelativeRotation *= enhance;
                    mCore.FrameData[i] = prPair;
                }

                HyperWiggleUtil.StableOffset(mCore.FrameData);

                mCore.UpdatePreview();
                mCore.UpdateTimeline();
            }

            GUILayout.EndHorizontal();
        }
    }
}